<template>
  <div
    class="home-continer"
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :style="`--innerHeight:${innerHeight}`"
  >
    <el-row :gutter="20">
      <el-col :span="24" style="margin-bottom: 20px">
        <Title :name="'年度统计'" :line="false">
          <div slot="append">
            <!-- <el-date-picker
              v-model="year1"
              type="year"
              size="small"
              placeholder="选择年"
              value-format="yyyy"
              @change="handlerchangeYear($event, 1)"
              :picker-options="pickerOptions"
            >
            </el-date-picker> -->
            <!-- {{ year1 }}年 -->
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="small"
              @click="handleExport(0)"
            >
              导出
            </el-button>
          </div>
          <tableCom ref="tableCom" :year="year1"></tableCom>
        </Title>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24" style="margin-bottom: 20px">
        <Title :name="'综表汇总数据'" :line="false">
          <div slot="append">
            <!-- <el-date-picker
              v-model="year1"
              type="year"
              size="small"
              placeholder="选择年"
              value-format="yyyy"
              @change="handlerchangeYear($event, 1)"
              :picker-options="pickerOptions"
            >
            </el-date-picker> -->
            <!-- {{ year1 }}年 -->
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="small"
              @click="handleExport(1)"
              style="margin-right: 20px"
            >
              导出
            </el-button>
            <el-date-picker
              v-model="year5"
              type="year"
              placeholder="请选择年份"
              size="small"
              :value-format="'yyyy'"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
          <!-- <table2></table2> -->
          <table5 ref="table5" :year="year5"></table5>
        </Title>
      </el-col>
    </el-row>
    <el-row v-if="overlap" :gutter="20">
      <el-col :span="24" style="margin-bottom: 20px">
        <Title :name="'非办公用能数据汇总'" :line="false">
          <div slot="append">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="small"
              @click="handleExport(2)"
              style="margin-right: 20px"
            >
              导出
            </el-button>
            <el-date-picker
              v-model="year6"
              type="year"
              placeholder="请选择年份"
              size="small"
              :value-format="'yyyy'"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
          <table6 ref="table6" :year="year6"></table6>
        </Title>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24" style="margin-bottom: 20px">
        <Title :name="'办公房间计量汇总'" :line="false">
          <div slot="append">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="small"
              @click="handleExport(3)"
              style="margin-right: 20px"
            >
              导出
            </el-button>
            <el-date-picker
              v-model="year7"
              type="year"
              placeholder="请选择年份"
              size="small"
              :value-format="'yyyy'"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
          <table4 ref="table4" :year="year7"></table4>
        </Title>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-if="show4">
      <el-col :span="24">
        <Title :name="'计量设备档案信息'" :line="false">
          <div slot="append">
            <!-- <el-date-picker
              v-model="year1"
              type="year"
              size="small"
              placeholder="选择年"
              value-format="yyyy"
              @change="handlerchangeYear($event, 1)"
              :picker-options="pickerOptions"
            >
            </el-date-picker> -->
            <!-- {{ year1 }}年 -->
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="small"
              @click="handleExport(4)"
            >
              导出
            </el-button>
          </div>
          <table3 ref="table3"></table3>
        </Title>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px" :gutter="20">
      <el-col :span="12">
        <Title :name="'年度能耗'" :line="false">
          <div slot="append">
            <!-- <el-date-picker
              v-model="year2"
              type="year"
              size="small"
              placeholder="选择年"
              value-format="yyyy"
              @change="handlerchangeYear($event, 2)"
              :picker-options="pickerOptions"
            >
            </el-date-picker> -->
            {{ year2 }}年
          </div>
          <echarts1 style="width: 100%" v-if="show1" ref="echarts1"></echarts1>
          <el-empty
            v-if="!show1"
            style="width: 100%; height: 350px"
            description="暂无数据"
          ></el-empty>
        </Title>
      </el-col>
      <el-col :span="12">
        <Title :name="'用能预算'" :line="false">
          <div slot="append">
            <!-- <el-date-picker
              v-model="year4"
              type="year"
              size="small"
              placeholder="选择年"
              value-format="yyyy"
              @change="handlerchangeYear($event, 4)"
              :picker-options="pickerOptions"
            >
            </el-date-picker> -->
            {{ year4 }}年
          </div>
          <div class="budget-area">
            <div class="top">
              <div
                v-for="(item, index) in budgetArr"
                :key="index"
                class="budget-item"
              >
                <span>{{ item.label }}:</span>
                <span>{{ item.value }}</span>
                <span>{{ item.unit }}</span>
              </div>
            </div>
            <div class="bottom">
              <echarts3 v-if="show3" ref="echarts3"></echarts3>
              <el-empty
                v-if="!show3"
                style="width: 100%; height: 350px"
                description="暂无数据"
              ></el-empty>
            </div>
          </div>
        </Title>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px" :gutter="20">
      <el-col :span="12">
        <Title :name="'用电统计'" :line="false">
          <div slot="append">
            <tabCom @handlerChnagetab="handlerChnagetab"></tabCom>
          </div>
          <echarts4 ref="echarts4"></echarts4>
          <el-empty
            v-if="!show1"
            style="width: 100%; height: 350px"
            description="暂无数据"
          ></el-empty>
        </Title>
      </el-col>
      <el-col :span="12">
        <Title :name="'用水统计'" :line="false">
          <div slot="append">
            <tabCom @handlerChnagetab="handlerChnagetab2"></tabCom>
          </div>
          <echarts5 ref="echarts5"></echarts5>
          <el-empty
            v-if="!show1"
            style="width: 100%; height: 350px"
            description="暂无数据"
          ></el-empty>
        </Title>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px" :gutter="20">
      <el-col :span="12">
        <Title :name="'碳排统计'" :line="false">
          <div slot="append">
            <tabCom @handlerChnagetab="handlerChnagetab3"></tabCom>
          </div>
          <echarts6 ref="echarts6"></echarts6>
          <el-empty
            v-if="!show1"
            style="width: 100%; height: 350px"
            description="暂无数据"
          ></el-empty>
        </Title>
      </el-col>
      <el-col :span="12">
        <Title :name="'消费统计'" :line="false">
          <div slot="append">
            <tabCom @handlerChnagetab="handlerChnagetab4"></tabCom>
          </div>
          <echarts7 ref="echarts7"></echarts7>
          <el-empty
            v-if="!show1"
            style="width: 100%; height: 350px"
            description="暂无数据"
          ></el-empty>
        </Title>
      </el-col>
    </el-row>
    <!-- <el-row style="margin-top: 20px" :gutter="20">
      <el-col :span="12">
        <Title class="rank-area" :name="'同行业排名'" :line="false">
          <div slot="append">
            <el-date-picker
              v-model="year3"
              type="year"
              size="small"
              placeholder="选择年"
              value-format="yyyy"
              @change="handlerchangeYear($event, 3)"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
          <div class="change-button" v-if="show2">
            <div
              class="change-button-item"
              v-for="(item, index) in BrchangeArr"
              :key="index"
              @click="handlerChangeBR(item.value)"
            >
              <img
                v-if="item.value == balckORred"
                src="@/assets/images/circle2.png"
                alt=""
              />
              <img v-else src="@/assets/images/circle1.png" alt="" />
              <span
                :class="[
                  'name',
                  item.value === balckORred ? 'chose' : 'nochose',
                ]"
              >
                {{ item.name }}
              </span>
            </div>
          </div>
          <echarts2 v-if="show2" ref="echarts2"></echarts2>
          <el-empty
            v-if="!show2"
            style="width: 100%; height: 350px"
            description="暂无数据"
          ></el-empty>
        </Title>
      </el-col>
      <el-col :span="12"></el-col>
    </el-row> -->
  </div>
</template>

<script>
import tableCom from "@/views/work/index/components/table.vue";
import table2 from "@/views/work/index/components/table2.vue";
import table3 from "@/views/work/index/components/table3.vue";
import table4 from "@/views/work/index/components/table4.vue";
import table5 from "@/views/work/index/components/table5.vue";
import table6 from "@/views/work/index/components/table6.vue";
import echarts1 from "@/views/work/index/components/echarts1.vue";
import echarts2 from "@/views/work/index/components/echarts2.vue";
import echarts3 from "@/views/work/index/components/echarts3.vue";
import echarts4 from "@/views/work/index/components/echarts4.vue";
import echarts5 from "@/views/work/index/components/echarts5.vue";
import echarts6 from "@/views/work/index/components/echarts6.vue";
import echarts7 from "@/views/work/index/components/echarts7.vue";
import tabCom from "@/views/work/index/components/tab.vue";

import { dealElectricity, deepClone } from "@/utils/index";
import { exportExcel } from "@/utils/xlsx";
import {
  getenergyYear,
  getEnergyFeeStatisticV2,
  getRedandBlack,
  getYearTotalEnergy,
  carbonStatistic,
  energyFeeStatistic,
} from "@/api/general/index.js";
import { getInfo } from "@/api/login";
import auth from "@/plugins/auth";
export default {
  components: {
    tableCom,
    echarts1,
    echarts2,
    echarts3,
    echarts4,
    echarts5,
    echarts6,
    echarts7,
    tabCom,
    table2,
    table3,
    table4,
    table5,
    table6,
  },
  data() {
    return {
      tab: 1,
      innerHeight: null,
      dataList: [],
      show1: false,
      show2: true,
      show3: true,
      show4: true,
      year1: null,
      year2: null,
      year3: null,
      year4: null,
      year5: null,
      year6: null,
      year7: null,
      pickerOptions: {
        disabledDate: (time) => {
          let thisYear = new Date().getFullYear();
          if (time.getFullYear() > thisYear) {
            return true;
          } else {
            return false;
          }
        },
      },
      balckORred: true, // 红黑榜 true：红 false：黑
      BrchangeArr: [
        {
          name: "红榜",
          value: true,
        },
        {
          name: "黑榜",
          value: false,
        },
      ],
      red: {
        xData: [],
        yData: [],
      },
      black: {
        xData: [],
        yData: [],
      },
      // 用能预算统计
      budgetArr: [
        {
          label: "总费用",
          value: 0,
          unit: "万元",
        },
        {
          label: "已用",
          value: 0,
          unit: "万元",
        },
        {
          label: "结余",
          value: 0,
          unit: "万元",
        },
      ],
      overlap: false,
    };
  },
  created() {
    this.getDeptIds();
    this.getYear();
    this.getMypremi();
  },
  mounted() {
    this.handlerChnagetab(1);
    this.handlerChnagetab2(1);
    this.handlerChnagetab3(1);
    this.handlerChnagetab4(1);
    this.dataGive();
    this.calcinnerHeight();
  },
  methods: {
    // 获取自己的角色权限字符
    getMypremi() {
      if (auth.hasPermi("index:energy:nonofficial")) {
        this.overlap = true;
      } else {
        this.overlap = false;
      }
      // let myroles = this.$store.state.user.roles; // 是个数组
      // let okArr = ["admin","13567698882","13868208180"]; // 可以显示的角色权限字符的集合
      // this.overlap = this.hasOverlap(myroles, okArr);
    },
    // 使用Set数据结构和some方法判断两个数组内容是否有重合
    hasOverlap(arr1, arr2) {
      const set = new Set(arr1);
      return arr2.some((item) => set.has(item));
    },
    handleExport(flage) {
      let deptName = this.$store.state.user.deptName;
      let cols = [{ wpx: 240 }];
      if (flage == 1) {
        let fileName = deptName + this.year5 + "年综表汇总数据";
        exportExcel(this.$refs.table5, fileName, cols);
      } else if (flage == 2) {
        let fileName = deptName + this.year6 + "非办公用能数据汇总";
        exportExcel(this.$refs.table6, fileName, cols);
      } else if (flage == 3) {
        let fileName = deptName + this.year7 + "办公房间计量汇总";
        exportExcel(this.$refs.table4, fileName, cols);
      } else if (flage == 0) {
        let fileName = deptName + this.year1 + "年度统计";
        exportExcel(this.$refs.tableCom, fileName, cols);
      } else if (flage == 4) {
        let fileName = deptName + this.year4 + "计量设备档案信息";
        exportExcel(this.$refs.table3, fileName, cols);
      }
    },
    async getDeptIds() {
      const res = await getInfo();
      let flag = res.user.regionFlag;
      this.show4 = null == flag ? true : flag == "0" ? false : true;
    },
    handlerChnagetab(value) {
      getYearTotalEnergy({
        energyType: 0,
        statisticalCycle: value,
      })
        .then((res) => {
          if (res.code === 200) {
            this.$refs.echarts4.initChart(res?.data ?? {});
          }
        })
        .catch((err) => {});
    },
    handlerChnagetab2(value) {
      getYearTotalEnergy({
        energyType: 1,
        statisticalCycle: value,
      })
        .then((res) => {
          if (res.code === 200) {
            this.$refs.echarts5.initChart(res?.data ?? {});
          }
        })
        .catch((err) => {});
    },
    handlerChnagetab3(value) {
      carbonStatistic({
        statisticalCycle: value,
      })
        .then((res) => {
          if (res.code === 200) {
            this.$refs.echarts6.initChart(res?.data ?? {});
          }
        })
        .catch((err) => {});
    },
    handlerChnagetab4(value) {
      energyFeeStatistic({
        statisticalCycle: value,
      })
        .then((res) => {
          if (res.code === 200) {
            this.$refs.echarts7.initChart(res?.data ?? {});
          }
        })
        .catch((err) => {});
    },
    calcinnerHeight() {
      this.innerHeight = window.innerHeight - 75 + "px";
    },
    getYear() {
      let year = new Date().getFullYear();
      this.year1 = String(year);
      this.year2 = String(year);
      this.year3 = String(year);
      this.year4 = String(year);
      this.year5 = String(year);
      this.year6 = String(year);
      this.year7 = String(year);
    },
    handlerchangeYear(value, falge) {
      // console.log(value, falge);
      switch (falge) {
        case 1:
          // 年度统计
          break;
        case 2:
          // 年度能耗
          this.echarts1Data();
          break;
        case 3:
          // 同行业排名
          this.echarts2Data();
          break;
        case 4:
          // 用能预算
          this.requestEnergyFeeStatisticV1();
          break;
      }
    },
    dataGive() {
      this.echarts1Data();
      this.requestEnergyFeeStatisticV1();
      this.echarts2Data();
    },
    // 年度能耗
    echarts1Data() {
      let yData = [
        {
          name: "单位面积综合能耗(kgce/m²)",
          data: [],
        },
        {
          name: "人均综合能耗(kgce/p)",
          data: [],
        },
        {
          name: "人均水耗(t/p)",
          data: [],
        },
        {
          name: "碳排量(kgCO2)",
          data: [],
        },
      ];
      let xData = [];
      let query = {
        year: this.year2,
      };
      getenergyYear(query)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            this.show1 = true;
            arr.map((item) => {
              xData.push(item.month + "月");
              yData[0].data.push(item?.areaAvgKgce ?? 0);
              yData[1].data.push(item?.personalAvgKgce ?? 0);
              yData[2].data.push(item?.personalAvgWater ?? 0);
              yData[3].data.push(item?.personalAvgCo2 ?? 0);
            });
            this.$nextTick(() => {
              this.$refs.echarts1.lineCharts(yData, xData);
            });
          } else {
            this.show1 = false;
          }
        })
        .catch(() => {
          this.show1 = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 同行业排名
    echarts2Data() {
      let query = {
        year: this.year3,
      };
      this.red = {
        xData: [],
        yData: [],
      };
      this.black = {
        xData: [],
        yData: [],
      };
      getRedandBlack(query)
        .then((res) => {
          // console.log(res, 444);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.data ?? [];
          if (arr.length > 0) {
            if (arr[0].length > 0 && arr[1].length > 0) {
              this.show2 = true;
              arr[0].map((item) => {
                this.red.xData.push(item.value);
                this.red.yData.push(item.deptName);
              });
              arr[1].map((item) => {
                this.black.xData.push(item.value);
                this.black.yData.push(item.deptName);
              });
              this.$nextTick(() => {
                this.$refs.echarts2.initChart(this.red.yData, this.red.xData);
              });
            } else {
              this.show2 = false;
            }
          } else {
            this.show2 = false;
          }
        })
        .catch(() => {
          this.show2 = false;
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 用能预算
    requestEnergyFeeStatisticV1() {
      let xData = [];
      let seriesData = [];
      let query = {
        year: this.year4,
      };
      getEnergyFeeStatisticV2(query)
        .then((res) => {
          // console.log(res, "33333");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let xArr = res?.data?.xaxisData ?? [];
          if (xArr.length > 0) {
            xArr.map((item) => {
              let obj = item + "月";
              xData.push(obj);
            });
          }
          // 今年
          let yObj = res?.data?.seriesData[0] ?? {
            name: "今年",
            data: [
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
            ],
          };
          let useNum = 0;
          if (yObj.data.length > 0) {
            yObj.data.map((item) => {
              useNum += Number(item);
            });
          }
          let totalFee = res?.data?.totalFee ?? 0;
          this.getBudgetData(useNum, totalFee);
          seriesData.push(yObj);
          // 去年
          let yObj2 = res?.data?.seriesData[1] ?? {
            name: "去年",
            data: [
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
              "0.00",
            ],
          };
          seriesData.push(yObj2);
          this.$refs.echarts3.initChart(xData, seriesData);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    getBudgetData(useNum, totalFee) {
      let allNum = totalFee;
      let arr0 = this.budgetDataDeal(allNum);
      let arr1 = this.budgetDataDeal(useNum);
      let arr2 = this.budgetDataDeal(Math.abs(allNum - useNum));
      this.budgetArr[0].value = arr0[0];
      this.budgetArr[0].unit = arr0[1];
      this.budgetArr[1].value = arr1[0];
      this.budgetArr[1].unit = arr1[1];
      if (allNum - useNum >= 0) {
        this.budgetArr[2].value = arr2[0];
        this.budgetArr[2].unit = arr2[1];
      } else {
        this.budgetArr[2].value = "-" + String(arr2[0]);
        this.budgetArr[2].unit = arr2[1];
      }
    },
    budgetDataDeal(value) {
      let result = [];
      // if (value < 10000) {
      result[0] = dealElectricity(value, 1, 2, "number");
      result[1] = "元";
      // } else if (value >= 10000 && value < 100000000) {
      //   result[0] = dealElectricity(value, 10000, 2, "number");
      //   result[1] = "万元";
      // } else if (value >= 100000000) {
      //   result[0] = dealElectricity(value, 100000000, 2, "number");
      //   result[1] = "亿元";
      // }
      return result;
    },
    handlerChangeBR(value) {
      this.balckORred = value;
      let ydata = [];
      let xdata = [];
      if (this.balckORred) {
        ydata = this.red.yData;
        xdata = this.red.xData;
      } else {
        ydata = this.black.yData;
        xdata = this.black.xData;
      }
      this.$refs.echarts2.initChart(ydata, xdata);
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/styles/mixin.scss";
.home-continer {
  height: var(--innerHeight);
  padding: 20px;
  overflow-y: scroll;
  @include scrollBar3(hsla(220, 4%, 58%, 0.9));
  .rank-area {
    position: relative;

    .change-button {
      position: absolute;
      top: 14px;
      z-index: 10;
      height: 15px;
      display: flex;
      .change-button-item {
        cursor: pointer;
        display: flex;
        align-items: center;
        margin-right: 10px;
        img {
          width: 15px;
          height: 15px;
          margin-right: 4px;
        }
        .name {
          line-height: 15px;
          font-size: 16px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 500;
          color: #000000;
        }
        .chose {
          color: #10b767;
          font-weight: bold;
        }
      }
    }
  }
  .budget-area {
    width: 100%;
    height: 100%;
    position: relative;
    .top {
      position: absolute;
      top: -10px;
      width: 100%;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      .budget-item {
        font-size: 18px;
        font-weight: 600;
        line-height: 20px;
        color: #000000;
        span {
          &:nth-child(2) {
            color: #059bab;
          }
        }
      }
    }
  }
}
</style>
